package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.common.exception.CustomException;
import com.heima.model.admin.dtos.UserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vos.AdUserVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;


@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {

    /**
     * 用户登录
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult login(UserDto userDto) {
        String name = userDto.getName();
        String password = userDto.getPassword();
        //判断数据是否合法
        if (userDto == null || StringUtils.isBlank(name) || StringUtils.isBlank(password)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询数据库中是否有该用户
        LambdaQueryWrapper<AdUser> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(AdUser::getName, name);
        AdUser user = getOne(wrapper);
        if (user == null) {
            CustomException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "当前用户不存在！！！");
        }
        //将密码加密，核对数据库中加密后的密码
        String md5Pwd = DigestUtils.md5DigestAsHex((password + user.getSalt()).getBytes());
        wrapper.eq(AdUser::getPassword, md5Pwd);
        AdUser one = getOne(wrapper);
        if (one == null) {
            CustomException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //判断用户状态是否为9
        if (user.getStatus().intValue() != 9) {
            CustomException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR);
        }

        user.setLoginTime(new Date());
        updateById(user);
        //如果没有token则生成token
        String token = AppJwtUtil.getToken(Long.valueOf(user.getId()));
        AdUserVO userVO = new AdUserVO();
        BeanUtils.copyProperties(user, userVO);
        HashMap<String, Object> map = new HashMap<>();
        map.put("user", userVO);
        map.put("token", token);
        //返回结果
        return ResponseResult.okResult(map);
    }

    /**
     * 注册
     */
    @Override
    public ResponseResult register(AdUser adUser) {
        String userName = null;
        String password = null;
        //判断数据是否合法
        if (adUser == null || org.apache.commons.lang3.StringUtils.isBlank(userName = adUser.getName()) || org.apache.commons.lang3.StringUtils.isBlank(password = adUser.getPassword())) {
            CustomException.cust(AppHttpCodeEnum.PARAM_INVALID, "用户名和密码不能为空！！！");
        }
        //查询用户名在数据库中是否存在
        LambdaQueryWrapper<AdUser> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(AdUser::getName, userName);
        AdUser one = getOne(wrapper);
        if (one != null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "当前用户名已经存在");
        }
        //加密密码，存入数据库
        //获取盐
        String salt = RandomStringUtils.randomAlphanumeric(8);
        String saltPwd = DigestUtils.md5DigestAsHex((password + salt).getBytes());
        adUser.setPassword(saltPwd);
        adUser.setCreatedTime(new Date());
        adUser.setStatus(9);
        adUser.setSalt(salt);
        save(adUser);
        return ResponseResult.okResult();
    }
}
